/*
 * CUdpMediaCaster.h
 *
 *  Created on: 2016年4月23日
 *      Author: terry
 */

#ifndef CUDPMEDIACASTER_H_
#define CUDPMEDIACASTER_H_

#include "RtpMediaCaster.h"
#include "TThread.h"
#include "TEvent.h"
#include "TCriticalSection.h"
#include <deque>
#include "RtpPackager.h"
#include "Socket.h"
#include "TByteBuffer.h"
#include "CasterDelay.h"
#include "NetAddress.h"
#include "MediaPacketQueue.h"

namespace av
{

typedef std::shared_ptr< RtpPackager >		RtpPackagerPtr;
typedef std::deque< NetAddress >        RtpTargetArray;


class CUdpMediaCaster: public RtpMediaCaster , public RtpPackagerSink, public comn::Thread
{
public:
	CUdpMediaCaster();
	virtual ~CUdpMediaCaster();

	virtual int open(const std::string& ip, uint16_t port, int codec, int clockRate, int payload, int ssrc);

	virtual void close();

	virtual bool isOpen();

	virtual void setID(int id);

	virtual int getID();

	virtual bool addTarget(const std::string& ip, uint16_t port);

	virtual void removeTarget(const std::string& ip, uint16_t port);

	virtual size_t getTargetCount();

	virtual void removeAllTarget();


    virtual void onMediaFormat(const MediaFormat& fmt);

    virtual void onMediaPacket(MediaPacketPtr& pkt);

    virtual void onMediaEvent(int event);

    NetAddress getLocalAddr();
    NetAddress getTargetAt(size_t idx);
    void removeTargets();

protected:
    virtual int run();
    virtual void doStop();

    virtual void onSlicePacket(const RtpPacket& pkt);

    bool openRtpSession(uint16_t port);
	void closeRtpSession();

	void clearCache();

	void sendPacket(MediaPacketPtr& pkt, double delayRate);

	void sendPacket(const RtpPacket& packet);

	void timedwait(int ms);

    RtpPackager* createPackager(int codec);

protected:
	comn::Socket    m_socket;
	comn::ByteBuffer    m_buffer;

	NetAddress	m_addr;
	MediaPacketQueue    m_pktQueue;

	RtpTargetArray	m_targets;
	comn::CriticalSection	m_cs;

	int64_t 	m_packetCount;
	uint32_t    m_lastTime;

	RtpPackagerPtr	m_packager;

	uint16_t    m_seq;
	uint32_t    m_ssrc;
	uint8_t m_payload;

	uint32_t    m_initTime;

	int64_t     m_lastPktTime;  /// 上一帧的时间戳 
	comn::Event m_eventDelay;
	uint32_t    m_delayCount;

	CasterDelay m_casterDelay;
	int	m_id;



};



} /* namespace av */

#endif /* CUDPMEDIACASTER_H_ */
